using System;
using System.IO;

namespace PackageResources.Pack
{
    public static class PathChecker
    {
        /// <summary>
        /// 检查路径是否合法
        /// </summary>
        /// <returns></returns>
        public static void CheckDirectoryExisting(string directoryPath)
        {
            if (!Directory.Exists(directoryPath))
            {
                throw new Exception("当前输入的路径不存在，请检查后再试。");
            }
        }

        /// <summary>
        /// 获得正确的合包资源路径
        /// </summary>
        /// <returns></returns>
        public static void CheckPackagePath(string packagePath)
        {
            var exception = new Exception("打包文件目标路径有误,请检查.");
            if (packagePath != "")
            {
                packagePath = packagePath.Replace('\\', '/');
                //查看是否路径是否合法，并且是否在存在相应路径文件夹
                //传过来的是目录，不是路径，报错
                var pathSplit = packagePath.Split('/');
                if (pathSplit.Length > 0) //查看最后是否包含具体文件路径，如果不包含，就报错
                {
                    if (!pathSplit[pathSplit.Length - 1].Contains("."))
                    {
                        throw exception;
                    }
                }

                var directoryLength = packagePath.LastIndexOf('/');
                var directoryPath = packagePath.Substring(0, directoryLength);
                if (!Directory.Exists(directoryPath))
                {
                    try
                    {
                        Directory.CreateDirectory(directoryPath);
                    }
                    catch (Exception)
                    {
                        throw exception;
                    }
                }
            }

//            throw exception;
        }
        
        /// <summary>
        /// 检查相关文件是否已存在，并做处理
        /// </summary>
        public static void CheckFilesExit(string filePath)
        {
            //判断合并文件是否已经存在，如果存在则删除
            if (File.Exists(filePath))
            {
                throw new Exception($"文件{filePath}已存在");
            }
        }
    }
}